#include <stdio.h>
#include <string.h>

/**
示例 1:

输入: a = "11", b = "1"
输出: "100"
示例 2:

输入: a = "1010", b = "1011"
输出: "10101"
*/

// 反转传入的二进制字符串, 比如: "11101" => "10111"
void reserve(char* s) {
  // .....
}

char* addBinary(char* a, char* b)
{
  // 1.【逆序】从【低】位开始相加求和
  reserve(a);
  reserve(b);

  // 2. num1[i] + num2[i] 进位为【2】
  int len_a = strlen(a), len_b = strlen(b);
  int n = fmax(len_a, len_b), carry = 0, len = 0;
  char* ans = (char*)malloc(sizeof(char) * (n + 2)); // n+2 => 进位、'\0'
  for (int i = 0; i < n; ++i) // i 从 0 开始，所以前面需要【逆序】字符串
  {
    carry += i < len_a ? (a[i] == '1') : 0;
    carry += i < len_b ? (b[i] == '1') : 0;

    ans[len++] = carry % 2 + '0'; // 进位改为2
    carry /= 2;
  }

  // 3.
  if (carry) {
    ans[len++] = '1';
  }

  // 4.
  ans[len] = '\0';

  // 5.
  reserve(ans);

  return ans;
}

int main(int argc, char const *argv[])
{
  char* s = "1234";
  printf("s[0] = %c\n", s[0]);
  printf("s[1] = %c\n", s[1]);
  printf("s[2] = %c\n", s[2]);
  printf("s[3] = %c\n", s[3]);
}
